package com.song.oa.controller;


import com.google.code.kaptcha.Producer;
import com.song.oa.util.RedisUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController

public class AuthController {


    @Resource
    private Producer producer;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 图片验证码
     */
    @GetMapping("/captcha")
    public String captcha(HttpServletRequest request, HttpServletResponse response) throws  IOException {
        String code = producer.createText();
//        String key = UUID.randomUUID().toString();
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        String str = "data:image/jpeg;base64,";
        String base64Img = str + Base64.getEncoder().encodeToString(outputStream.toByteArray());
        this.redisUtil.setCacheObject("captcha", code, 1, TimeUnit.MINUTES);
        return base64Img;
    }

}
